<template>
  <div style="height: 100%" v-loading="loading">
    <div class="tabpane topcolor flexb othertop">
      <div class="flex">
        <a class="active fontz">CPU / NET</a>
        <div class="resources">
          <eos-resource />
        </div>
      </div>
    </div>
    <div class="jycenter flexb">
      <!-- 租借 -->
      <div class="xjmrbox">
        <el-form ref="xjFormMr"
          label-width="70px" size="mini">
          <!-- 租借/余额 -->
          <div class="flexb mb">
            <span class="color-lv">{{ $t('cpuNet.cpuNetLease1') }}</span>
            <span v-if="scatter && scatter.identity && scatter.chain === 'eos'">{{ $t('myWallet.balance') }}：{{eosBalance}}</span>
          </div>
          <!-- 租借类型 -->
          <el-form-item :label="$t('cpuNet.rentalType')">
            <div class="flexb zjType" style="width: 100%;">
              <div v-for="(item, index) in activeList"
                :key="index"
                class="tab"
                :class="{'active': index === active}"
                @click="handleChangeActive(index)">
                {{ item.label }}
              </div>
            </div>
          </el-form-item>
          <!-- 租借价格 -->
          <el-form-item :label="$t('cpuNet.rentalPrice')">
            <el-input :value="cpunetPrice" disabled>
              <span slot="suffix">EOS*{{cycle}}{{ $t('cpuNet.day') }} / EOS</span>
            </el-input>
          </el-form-item>
          <!-- 租借期限 -->
          <el-form-item :label="$t('cpuNet.rentalTerm')">
            <el-input :value="`${cycle}${$t('cpuNet.day')}`" disabled>
            </el-input>
          </el-form-item>
          <!-- 接收账户 -->
          <el-form-item :label="$t('newpos.receiveAccount')">
            <el-input v-model.trim="receiver" clearable :placeholder="$t('bosChain.pleaseInputAccount')">
              <template slot="prepend">EOS{{ $t('order.account') }}</template>
            </el-input>
          </el-form-item>
          <!-- 租借数量 -->
          <el-form-item :label="$t('cpuNet.rentalQuantity')" class="leaseNum">
            <el-input v-model="loanNumber" @input="handlePayMoneyChange"
            :placeholder="$t('cpuNet.enterRentalQuantity')"
            type="number" clearable :step="0.0001" :min="0.0001">
              <span slot="suffix">EOS({{active ? 'NET' : 'CPU'}})</span>
            </el-input>
          </el-form-item>
          <div class="totalNum" style="margin: -5px 0 8px 0;">
            {{ $t('cpuNet.cpuNetRent') }}: <span class="color-lv">{{loanPayment}}</span>
          </div>
          <!-- 续租周期 -->
          <el-form-item :label="$t('cpuNet.rentalRenewalPeriod')" class="cycle">
            <el-input-number v-model="cycleNumValue" :min="0" :step="cycle" step-strictly size="large"
            @change="handleChange">
            </el-input-number>
            <div class="mask">{{ cycleNumValue }} {{ $t('cpuNet.day') }}</div>
            <div class="cycleTip">
              <el-tooltip placement="bottom-end" effect="light">
                <div slot="content" class="cozyTipContent">
                  <p>{{ $t('cpuNet.cpuNetTip1') }}</p>
                  <p style="margin-top: 3px;">{{ $t('cpuNet.cpuNetTip2') }}</p>
                </div>
                <div class="cozyTip">
                  <i class="iconfont icon-huaban"></i>
                </div>
              </el-tooltip>
            </div>
          </el-form-item>
          <div class="totalNum" style="margin-top: -5px">
            {{ $t('cpuNet.rentRenewal') }}: <span class="color-lv">{{loanFund}}</span>
          </div>
          <!-- 租借 -->
          <el-form-item size="small" style="margin: 10px 0 0 0;">
            <div v-if="scatter">
              <el-button class="mrbtn" v-if="scatter.identity && chain === 'eos'"
              @click="handleAction">{{ $t('cpuNet.cpuNetLease') }}</el-button>
              <el-button class="mrbtn"
              v-else-if="scatter.identity && chain !== 'eos'"
              @click="handleWalletPermission">
                {{$t('bosChain.tradeTip1')}} EOS {{$t('bosChain.tradeTip2')}}
              </el-button>
              <el-button class="mrbtn" v-if="scatter && !scatter.identity">
                <span class="color-fff" @click="handleWalletPermission">{{$t('wallet.wpromis')}}</span>
              </el-button>
            </div>
          </el-form-item>
        </el-form>
      </div>
      <!-- 出租CPU -->
      <div class="czCpuBox">
        <div class="color-ho czCaption">{{ $t('cpuNet.rentalCpu') }}</div>
        <div class="mb20">
          {{ $t('cpuNet.rentalCpuTip1') }}
          <span class="buyRex">{{ $t('cpuNet.rentalCpuTip2') }}</span>
          {{ $t('cpuNet.rentalCpuTip3') }}
        </div>
        <div class="mb20">
          <span class="color-lv">{{ $t('cpuNet.buyRex1') }}</span>{{ $t('cpuNet.buyRex2') }}
        </div>
        <div class="mb20">
          <span class="color-ho">{{ $t('cpuNet.sellRex1') }}</span>{{ $t('cpuNet.sellRex2') }}{{ $t('cpuNet.sellRex3') }}
        </div>
        <div style="width: 270px; margin:152px auto 0">
          <el-button
          class="qrbtn"
          @click="$router.push({ name: 'rexExchange' })">{{ $t('cpuNet.goAndBuyRex') }}</el-button>
        </div>
      </div>
    </div>
    <!-- 确定弹窗 -->
    <el-dialog
      class="confirmDiaog"
      :title="$t('cpuNet.comfirm')"
      :close-on-click-modal="false"
      :visible.sync="confirmVisible"
      width="550px">
      <div class="confirmDiaogCont">
        <div class="confirmList flexb">
          <span>{{ $t('newpos.receiveAccount') }}</span>
          <span>{{params.receiver}}</span>
        </div>
        <div class="confirmList flexb">
          <span>{{ $t('cpuNet.rentalType') }}</span>
          <span>{{active ? 'NET' : 'CPU'}}</span>
        </div>
        <div class="confirmList flexb">
          <span>{{ $t('cpuNet.rentalQuantity') }}</span>
          <span>{{params.loanNumber}}</span>
        </div>
        <div class="confirmList flexb">
          <span>{{ $t('cpuNet.rentalTerm') }}</span>
          <span>30{{ $t('cpuNet.day') }}</span>
        </div>
        <div class="confirmList flexb">
          <span>{{ $t('cpuNet.cpuNetRent') }}</span>
          <span>{{params.loanPayment}}</span>
        </div>
        <div class="confirmList flexb"  v-if="parseFloat(params.loanFund, 0)">
          <span>{{ $t('cpuNet.rentalRenewalPeriod') }}</span>
          <span>{{ cycleNumValue }} {{ $t('cpuNet.day') }}</span>
        </div>
        <div class="confirmList flexb" v-if="parseFloat(params.loanFund, 0)">
          <span>{{ $t('cpuNet.rentRenewal') }}</span>
          <span>{{params.loanFund}}</span>
        </div>
        <div class="confirmList flexb lastList">
          <span>{{ $t('cpuNet.paymenTtotalRent') }}</span>
          <span class="color-lv">{{params.payMoeny}}</span>
        </div>
        <div class="mt">
          <el-button
          class="qrbtn"
          @click="handleSubmit"
          :loading="submitLoading"> {{ submitLoading ? $t('cpuNet.payLoading') : $t('cpuNet.confirmationPayment') }}</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios';
import { EosModel } from '@/utils/eos';
import { Decimal } from 'decimal.js';
import { toFixed, toNonExponential } from '@/utils/validate';
import ScatterPermission from '@/components/ScatterPermission';
import Agreement from '@/components/Agreement';
import EosResource from '@/components/EosResource'; // eos资源

export default {
  name: 'trading-center-bottom',
  components: {
    ScatterPermission,
    Agreement,
    EosResource
  },
  data() {
    return {
      cycle: 30, // 续租周期
      active: 0, // 0-cpu 1-net
      activeList: [
        {
          value: 0,
          label: 'CPU',
        },
        {
          value: 1,
          label: 'NET',
        }
      ],
      chain: 'eos',
      loading: false,
      submitLoading: false,
      accoutRes: '', // 账户余额等数据
      usedCpu: '', // cpu使用量
      totalCpu: '', // cpu总量
      cpu_weight: '',
      cpuPercent: 0, // cpu使用百分比
      cpuAddColor: 0, // cup余额不同显示颜色
      cpuShow: false, // 是否显示cpu
      nodeChecked: {}, // 当前节点
      getNodeClass: 'hidden',
      receiver: '', // 接收账户
      loanNumber: null, // 租借数量
      loanPayment: '0.0000 EOS', // 租借金额
      radio: 0,
      loanFund: '0.0000 EOS', // 续租租金
      confirmVisible: false, // 确认弹窗
      params: {
        payMoeny: '0.0000 EOS'
      },
      cycleNumValue: 0, // 租借周期值
    };
  },
  props: {
    eosBalance: String, // eos 余额
    symbolScience: String, // EOS SYS 环境变量
    rexBalance: null, // rex 余额
    cpunetPrice: Number,
    fundBalance: Number, // 储备金余额
    scatter: Object,
  },
  watch: {
    // 监听账户余额等数据
    '$store.state.app.nodeChecked.timer': function change() {
      const chain = this.$store.state.app.scatter.chain || 'eos';
      this.nodeChecked = this.$store.state.app.nodeChecked[chain];
    },
    'scatter.identity': function change(val) {
      this.chain = this.scatter.chain;
      if (val) {
        this.receiver = this.scatter.identity.accounts[0].name;
      }
    },
    confirmVisible: function change() {
      this.submitLoading = false;
    },
  },
  computed: {
  },
  created() {
  },
  destroyed() {
  },
  mounted() {
    this.chain = this.scatter.chain;
    if (this.scatter && this.scatter.identity) {
      this.receiver = this.scatter.identity.accounts[0].name;
    }
  },
  beforeDestroy() {
  },
  methods: {
    // 租借操作
    handleAction() {
      // 租金大于0.0001
      if (parseFloat(this.params.payMoeny, 0) < 0.0001) {
        this.$message.error(`${this.$t('cpuNet.cpuNetRent')} ≥ 0.0001`);
        return;
      }
      // 余额是否够
      if (parseFloat(this.fundBalance, 0) < parseFloat(this.params.payMoeny, 0)
      && parseFloat(this.eosBalance, 0) < parseFloat(this.params.payMoeny, 0)) {
        this.$message.error(this.$t('jy.error3'));
        return;
      }
      // 该账户是否存在
      this.handleValidateReceive().then((hasEosAccount) => {
        if (!hasEosAccount) {
          this.$message.error(this.$t('bosChain.accountNone', { chain: 'EOS' })); // 该账户不存在
          return;
        }
        let amount = 0;
        let loanNumber = parseFloat(this.loanNumber, 0);
        let loanFund = parseFloat(this.loanFund, 0);
        if (!loanNumber) {
          this.$message.error(this.$t('cpuNet.enterRentalQuantity'));
          return;
        }
        if (isNaN(loanNumber) || loanNumber < 0.0001) { // 请输入正确的数量
          this.$message.error(`${this.$t('public.inputRightNum')} ≥ 0.0001`);
          return;
        }
        if (parseFloat(this.params.payMoeny, 0) > parseFloat(this.fundBalance)) {
          amount = parseFloat(this.params.payMoeny, 0)
        }
        amount = `${toFixed(amount, 4)} ${this.symbolScience}`;
        loanNumber = `${toFixed(loanNumber, 4)} ${this.symbolScience}`;
        loanFund = `${toFixed(loanFund, 4)} ${this.symbolScience}`;
        const payMoeny = this.params.payMoeny
        this.params = {
          type: this.active, // 0-CPU, 1-NET
          receiver: this.receiver, // 接收账户
          amount, // 存入储备金数量
          loanNumber, // 租借数量
          loanPayment: this.loanPayment, // 租借金额
          loanFund, // 续租租金
          payMoeny, // 支付总租金
        }
        this.confirmVisible = true;
      });
    },
    // 确认支付操作
    handleSubmit() {
      this.submitLoading = true;
      EosModel.cpuTransaction(this.params, (res) => {
        this.submitLoading = false;
        if (res && res.broadcast) {
          this.$message.success(this.$t('newpos.successfulOperation'));
          this.confirmVisible = false;
          this.$emit('listenCenterBottom', 'refresh');
          return;
        }
        EosModel.handleScatterErrorBack(res);
      })
    },
    // 计算总租金
    handlePayMoneyChange() {
      let loanNumber = Number(this.loanNumber);
      // 只取4位小数位
      const str = loanNumber ? loanNumber.toString() : '';
      if (str.indexOf('.') > 0 && str.split('.')[1].length > 4) {
        loanNumber = str.match(/^\d*(\.?\d{0,4})/g)[0];
        setTimeout(() => {
          this.loanNumber = loanNumber;
        }, 300)
      }
      this.loanPayment = loanNumber ? toFixed(toNonExponential(loanNumber / this.cpunetPrice), 4) : 0; // 预计租金：数量 / 价格
      const cy = toFixed(toNonExponential(this.cycleNumValue / this.cycle), 4);
      // 已续租租金
      this.loanFund = toFixed(toNonExponential(Number(cy) * Number(this.loanPayment)), 4);
      const payMoeny = toNonExponential(Number(this.loanFund) + Number(this.loanPayment));
      this.loanPayment = `${toFixed(this.loanPayment, 4)} ${this.symbolScience}`;
      this.loanFund = `${toFixed(this.loanFund, 4)} ${this.symbolScience}`;
      this.params.payMoeny = `${toFixed(payMoeny, 4)} ${this.symbolScience}`;
    },
    // 租借周期变化事件
    handleChange(value) {
      this.cycleNumValue = value;
      const cy = Decimal.div(this.cycleNumValue, this.cycle);
      this.loanFund = Decimal.mul(cy, parseFloat(this.loanPayment, 0));
      const payMoeny = Decimal.add(this.loanFund, parseFloat(this.loanPayment, 0));
      this.params.payMoeny = `${toFixed(payMoeny, 4)} ${this.symbolScience}`;
      this.loanFund = `${toFixed(this.loanFund, 4)} ${this.symbolScience}`;
    },
    // 验证账户是否存在
    async handleValidateReceive() {
      const nodeChecked = this.$store.state.app.nodeChecked;
      const nodeobj = nodeChecked.eos;
      const kip = nodeobj.url;
      const accountParams = {
        account_name: this.receiver
      };
      const back = await axios.post(`${kip}/v1/chain/get_account`, JSON.stringify(accountParams)).then((result) => {
        if (result.status !== 200) return false;
        return true;
      }).catch(() => false);
      return back;
    },
    // tab 切换
    handleChangeActive(index) {
      this.active = index;
    },
    // 跳转cpu
    handleJumpCpu() {
      const language = this.$store.state.app.language;
      if (language === 'zh-CN' || language === 'zh-TW') {
        window.open('https://www.cpubaba.com');
      }
    },
    // 登录授权
    handleWalletPermission() {
      const checkWallet = localStorage.getItem('checkWallet');
      sessionStorage.setItem('checkWalletByChain', 'EOS');
      if (!Number(checkWallet)) {
        this.$emit('listenWalletPermission', true);
        return;
      }
      this.$emit('listenWalletLogin', true);
    },
    /*
    * 进度格式化
    * @params numb Number
    * @p 保留小数后几位
    */
    toFixed(numb, p) {
      return toFixed(numb, p);
    },
  },
};
</script>

<style lang="scss" scoped>
@import "@/assets/css/variables.scss";

$-color-lv: #67C269;
$-color-ho: #EE1443;
$-color-black: #7b8db9;
$-color-lan: #278EDA;
.litterDelay {
  color: #333 !important;
}
.nodeDelay {
  color: $-color-lv !important;
}
.mediumLatency {
  color: #FF9800 !important;
}
.highLatency {
  color: #E51C23 !important;
}
.mb20 {
  margin-bottom: 20px !important;
}
.color-lv {
  color: $-color-lv;
}
.color-ho {
  color: $-color-ho;
}
.topcolor {
  background: $-topcolorf7;
}
.budgetBuy {
  margin-bottom: 0 !important;
  color: #999;
}
.fontx {
  cursor: pointer;
}
.cpuTip {
  margin-right: 42px;
  height: 42px;
}
.cpuPercent {
  cursor: pointer;
  color: #333;
  .icon-CPU {
    font-size: 23px;
    color: $-color-lv;
    margin-right: 6px;
  }
  span {
    font-size: 13px;
  }
}
.mcbtn, .mrbtn {
  height: 40px;
  font-size: 14px;
  padding: 9px 0px
}

.mrbtn {
  width: 100%;
  color: #fff;
  background-color: $-color-lv;
  border-color: $-color-lv;
  -webkit-box-shadow: -1px 0 0 0 $-color-lv;
  box-shadow: -1px 0 0 0 $-color-lv;
}
.mcbtn {
  width: 100%;
  color: #fff;
  background-color: $-color-ho;
  border-color: $-color-ho;
  -webkit-box-shadow: -1px 0 0 0 $-color-ho;
  box-shadow: -1px 0 0 0 $-color-ho;
}
.qrbtn {
  width: 100%;
  color: #fff;
  background-color: $-color-lan;
  border-color: $-color-lan;
  -webkit-box-shadow: -1px 0 0 0 $-color-lan;
  box-shadow: -1px 0 0 0 $-color-lan;
}
.noticebox {
  margin-left: 10px;

  .icon-wifiwofi {
    display: inline-block;
    // vertical-align: top;
    height: 20px;
    width: 23px;
    font-size: 24px;
    margin-top: -6px;
    cursor: pointer;
  }

  .litterDelay {
    display: inline-block;
  }
}

.redColor {
  color: #EE1443 !important;
}
.orangeColor {
  color: #FF9800 !important;
}

.jycenter {
  position: relative;
  padding: 20px 50px;
  height: 500px;

  &::before {
    content: ' ';
    position: absolute;
    width: 1px;
    height: 80%;
    background: #dedede;
    left: 50.2%;
    top: 50%;
    transform: translateY(-50%);
  }

  /deep/ .el-form-item--mini.el-form-item {
    margin-bottom: 8px;
  }

  /deep/ .el-input--mini {
    .el-input__inner {
      height: 40px;
      line-height: 40px;
      font-size: 14px;
    }
  }
  /deep/ .el-form-item--mini {
    .el-form-item__label {
      height: 40px;
      line-height: 40px;
      font-size: 14px;
    }
    .el-form-item__content {
      margin-left: 75px !important;
    }
  }

  /deep/ .el-input__suffix {
    height: auto;
    line-height: 40px;
    font-size: 13px;
  }

  /deep/ .el-slider__button-wrapper {
    z-index: 9;
  }

  .xjmrbox {
    padding: 0px 10px 0 0;
    position: relative;
    width: 350px;
    max-width: 350px;
    margin-left: 40px;
    font-size: 14px;
    min-height: 400px;

    /deep/ .el-input-group__prepend {
      padding: 0 15px;
    }

    .zjType {

      .tab {
        position: relative;
        display: inline-block;
        width: 47%;
        padding: 5px 0;
        border-radius: 3px;
        color: #333;
        border: 1px solid #e4e7ed;
        text-align: center;
        cursor: pointer;
      }

      .tab:first-child {
        margin-right: 15px;
      }

      .active {
        color: $-color-lv;
        border-color: $-color-lv;
      }
    }

    .leaseNum {
      /deep/ .el-input__inner {
        padding-right: 65px;
      }

    }
    .totalNum {
      text-align: right;
    }

    .zjBtn {
      color: #fff;
      background: $-color-lv;
      margin: 10px 0 0 75px;
      padding-top: 7px;
      padding-bottom: 7px;
      text-align: center;
      cursor: pointer;
    }

    .cycle {
      position: relative;
      /deep/ .el-input-number {
        width: 100%;
      }

      .mask {
        position: absolute;
        width: 183px;
        height: 38px;
        left: 41px;
        top: 1px;
        background: #fff;
        z-index: 10;
        text-align: center;
        line-height: 38px;
      }

      .cycleTip {
        position: absolute;
        right: -22px;
        top: 5px;

        .cozyTip {
          cursor: pointer;
        }
      }
    }
  }

  .czCpuBox {
    font-size: 14px;
    // display: flex;
    align-items: flex-end;
    width: 340px;
    max-width: 340px;
    min-height: 400px;

    .czCaption {
      margin-bottom: 35px;
    }

    .buyRex {
      margin-bottom: 20px;
      color: #278EDA;
    }

    .buyRexBtn {
      width: 223px;
      background: #278EDA;
      color: #fff;
      line-height: 42px;
      text-align: center;
      margin: 150px auto 0;
      cursor: pointer;
    }
  }
}

.cozyTipContent {
  width: 385px;
  font-size: 12px;
  line-height: 25px;
  padding: 5px;
  font-family: SourceHanSansSC-regular;
  color: #999;
}

.cozyTip {
  margin-top: 4px;
  float: right;
  font-size: 12px;
  color: #999;
  font-family: SourceHanSansSC-regular;
  cursor: pointer;
}

.confirmDiaog {
  /deep/ .el-dialog__header {
    text-align: center;
    padding-top: 23px;
  }

  .confirmDiaogCont {
    padding: 0 80px;

    .confirmList {
      color: #333;
      margin-bottom: 15px;

      span:nth-child(1) {
        flex: 1;
      }

      span:nth-child(2) {
        flex: 2;
      }

      &.targetList {
      }

      &.lastList {
        padding-top: 15px;
        position: relative;

        &::after {
          content: ' ';
          position: absolute;
          top: 3px;
          left: 50%;
          width: 430px;
          height: 1px;
          transform: translateX(-50%);
          background: #e4e7ed;
        }

        .color-lv {
          font-size: 16px;
        }
      }
    }

    .confirmDiaogBtn {
      // width: 223px;
      background: $-color-lan;
      color: #fff;
      line-height: 50px;
      text-align: center;
      margin: 30px auto 0;
      cursor: pointer;
    }
  }
}

.theme-1B1D27 {
  .jycenter {
    &::before {
      background: rgba(255, 255, 255, 0.1) !important;
    }
  }

  .tab {
    color: rgba(255, 255, 255, 0.8) !important;
    border-color: rgba(255, 255, 255, 0.4) !important;
  }

  .tab.active {
    color: $-color-lv !important;
    border-color: $-color-lv !important;
  }

  .cpuPercent, .noticebox {
    span {
      color: rgba(255, 255, 255, 0.9) !important;
    }
  }

  .trbtable {
    background: none;
  }
  .mrmcbox {
    &::before {
      background: rgba(255, 255, 255, .1);
    }
  }
  .topcolor {
    background: $-topcolor2;
  }

  .tabpane {
    a {
      &.active {
        background: $-black1;
      }
    }
  }

  .confirmList {
    color: rgba(255, 255, 255, .8) !important;
  }

  .trasfStop {
    background: $-black1
  }

  .mask {
    background: #152247 !important;
  }
}
</style>
